<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="./lib/bootstrap-3.3.7.css">
    <script src="./lib/vue.js"></script>
</head>
<body>
    <div id="app">

        <!-- 评论组件 -->
        <comment @func="loadComment"></comment>

        <ul class="list-group">
            <li class="list-group-item" v-for="item in list" :key="item.id">
                <span class="badge">评论人： {{ item.user }}</span>
                {{ item.content }}
            </li>
        </ul>
    </div>

    <template id="tmp1">
        <div>
            <div class="form-group">
                <label>评论人：</label>
                <input type="text" class="form-control" v-model="user">
            </div>
        
            <div class="form-group">
                <label>评论内容：</label>
                <textarea class="form-control" v-model="content"></textarea>
            </div>
        
            <div class="form-group">
                <input type="button" value="发表评论" class="btn btn-primary" @click="addComment">
            </div>
        </div>
    </template>

    <script>
        var comment = {
            template : '#tmp1',
            data : function(){
                return {
                    user : '',
                    content : ''
                }
            },
            methods: {
                addComment(){
                    //获取子组件中的 user 和 content 值
                    let userComment = {id : Date.now() , user : this.user , content : this.content}
                    //获取 localStorage 存储的数据 
                    let list =  JSON.parse(localStorage.getItem('commentsList') || '[]')
                    //将添加的数据 追加到 总数据中
                    list.unshift(userComment)
                    //重新转化为字符串 存储到 localStorage 中
                    localStorage.setItem('commentsList',JSON.stringify(list))
                    this.user = this.content = ''
                    //调用 父组件中的 加载列表的方法
                    this.$emit('func')
                }
            }
        }

        new Vue({
            el : '#app',
            data : {
                list : [
                    // { id: Date.now(), user: '李白', content: '天生我材必有用' },
                    // { id: Date.now(), user: '江小白', content: '劝君更尽一杯酒' },
                    // { id: Date.now(), user: '小马', content: '我姓马， 风吹草低见牛羊的马' }
                ]
            },
            created() {
                this.loadComment()
            },
            methods : {
                loadComment(){
                    this.list = JSON.parse(localStorage.getItem('commentsList') || '[]')
                }

            },
            components : {
                comment
            }
        })
    
    </script>
</body>
</html>